package cn.jetpiece.cloud.log.app.modular.log.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.jetpiece.cloud.log.api.model.result.GatewayLogInfoResult;
import cn.jetpiece.cloud.log.api.GatewayLogApi;
import cn.jetpiece.cloud.log.api.model.params.GatewayLogParam;
import cn.jetpiece.cloud.log.api.model.query.GatewayLogQuery;
import cn.jetpiece.cloud.log.api.model.result.GatewayLogResult;
import cn.jetpiece.cloud.log.app.modular.log.entity.GatewayLog;
import cn.jetpiece.cloud.log.app.modular.log.service.GatewayLogService;
import cn.jetpiece.cloud.model.contants.ResponseMsgConstants;
import cn.jetpiece.cloud.model.page.PageResult;
import cn.jetpiece.cloud.model.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 网关日志控制器
 *
 * @author XuJZ
 */
@Slf4j
@RestController
public class GatewayLogController implements GatewayLogApi {

    private GatewayLogService gatewayLogService;

    @Autowired
    public void setGatewayLogService(GatewayLogService gatewayLogService) {
        this.gatewayLogService = gatewayLogService;
    }


    @Override
    public Result<String> add(GatewayLogParam param) {
        if (gatewayLogService.add(param)) {
            return Result.OK(ResponseMsgConstants.CREATE_SUCCESS);
        } else {
            return Result.error(ResponseMsgConstants.CREATE_ERROR);
        }
    }

    @Override
    public Result<String> delete(Long id, Date requestTimeStart) {
        if (gatewayLogService.lambdaUpdate().ge(GatewayLog::getRequestTime, requestTimeStart).eq(GatewayLog::getId, id).remove()) {
            return Result.OK(ResponseMsgConstants.DELETE_SUCCESS);
        } else {
            return Result.error(ResponseMsgConstants.DELETE_ERROR);
        }
    }

    @Override
    public Result<GatewayLogInfoResult> getInfo(Long id, Date requestTimeStart) {
        GatewayLog bean = gatewayLogService.lambdaQuery().ge(GatewayLog::getRequestTime, requestTimeStart).eq(GatewayLog::getId, id).one();
        if (bean == null) {
            return Result.OK();
        }
        GatewayLogInfoResult result = new GatewayLogInfoResult();
        BeanUtil.copyProperties(bean, result);
        return Result.OK(result);
    }


    @Override
    public Result<PageResult<GatewayLogResult>> page(GatewayLogQuery query) {
        return Result.OK(gatewayLogService.page(query));
    }

}
